package com.pedro.streamer.file

class Node<T>(var data: T) {
    var next: Node<T>? = null
}

class CircularLinkedList<T> {
    private var head: Node<T>? = null

    fun add(data: T) {
        val newNode = Node(data)
        if (head == null) {
            head = newNode
            newNode.next = head
        } else {
            var current = head
            while (current?.next != head) {
                current = current?.next
            }
            current?.next = newNode
            newNode.next = head
        }
    }

    fun remove(data: T?) {
        if (head == null) return

        var current = head
        var prev: Node<T>? = null

        do {
            if (current?.data == data) {
                if (current == head) {
                    if (current?.next == head) {
                        head = null
                    } else {
                        prev?.next = current?.next
                        head = current?.next
                    }
                } else {
                    prev?.next = current?.next
                }
                return
            }
            prev = current
            current = current?.next
        } while (current != head)
    }

    fun getNext(data: T?): T? {
        var current = head

        do {
            if (current?.data == data) {
                return current?.next?.data
            }
            current = current?.next
        } while (current != head)

        return null
    }

    fun clear() {
        if (head == null) return

        var current = head
        do {
            val nextNode = current?.next
            current?.next = null // 断开引用
            current = nextNode
        } while (current != head)

        head = null
    }

}
